package com.hdyg.sixg.activity.common;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.PopupWindow;

import com.hdyg.sixg.R;
import com.hdyg.sixg.app.MvpApplication;
import com.hdyg.sixg.mvp.base.BasePresenter;
import com.hdyg.sixg.ui.CustomProgressDialog;
import com.hdyg.sixg.util.CountDownTimerUtil;
import com.hdyg.sixg.util.LangUtil.MultiLanguageUtil;
import com.hdyg.sixg.util.LogUtils;
import com.hdyg.sixg.util.SysStyleUtil;
import com.hdyg.sixg.util.ToastUtil;
import java.util.Map;
import butterknife.ButterKnife;


/**
 * 基类  用于所有的activity继承
 *
 * @author
 * @time 2018/3/8 11:30
 */
public abstract class BaseActivity<V, T extends BasePresenter<V>> extends FragmentActivity {
    private ForceOffLineReceiver receive;
    public static final String UN_TOKEN_BROCAST = MvpApplication.getContext().getPackageName() + ".OFF";
    protected Context mContext;
    protected Bundle mBundle;
    protected T mPresenter; // Presenter 对象
    protected CustomProgressDialog progressDialog;
    protected InputMethodManager inputMethodManager;
    protected PopupWindow mPopupWindow;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setNoTitile();//取消标题的方法
        AppManager.getAppManager().addActivity(this);
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        // 沉浸状态栏
        steepStatusBar();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//设置竖屏显示
        setContentView(getLayoutId());
        mContext = this;
        ButterKnife.bind(this);
        createPresenter();
        if (mPresenter != null) {
            mPresenter.attachView((V) this);
        }
        initView();
        initData();

    }

    // api = 26时  兼容  ======== 开 始 =========
    @Override
    protected void attachBaseContext(Context newBase) {
        MultiLanguageUtil.autoUpdateLanguageEnviroment(newBase);
        super.attachBaseContext(newBase);
    }
    // ====================    结 束     ==================

    protected void hideSoftKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UN_TOKEN_BROCAST);
        receive = new ForceOffLineReceiver();
        registerReceiver(receive, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (receive != null) {
            unregisterReceiver(receive);
            receive = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        if (progressDialog != null) {
            progressDialog.cancel();
            progressDialog = null;
        }
        CountDownTimerUtil.getInstance().stopTimer();
        AppManager.getAppManager().finishActivity(this);
    }

    //设置沉浸式状态栏
    private void steepStatusBar() {
        //api >= 19
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //设置状态栏颜色
            SysStyleUtil.setStatusBarLightMode(this, android.R.color.transparent, false);
        }
    }

    protected abstract int getLayoutId();

    protected abstract void initView();

    protected abstract void initData();

    /**
     * 创建 Presenter 对象
     *
     * @return
     */
    protected abstract void createPresenter();

    public void setNoTitile() {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    }


    /**
     * 封装toast
     */
    public void toastNotifyShort(Object notify) {
        String str = null;
        if (notify instanceof String)
            str = notify.toString();
        else if (notify instanceof Integer)
            str = getResources().getString((Integer) notify);
        ToastUtil.show(str);
    }

    /**
     * activity 跳转[无参]
     *
     * @param className
     */
    public void startActivity(Class<?> className) {
        startActivity(className, null);
    }

    /**
     * activity 跳转[有参]
     *
     * @param className
     * @param bundle
     */
    public void startActivity(Class<?> className, Bundle bundle) {
        Intent mIntent = new Intent();
        mIntent.setClass(this, className);
        if (bundle != null) {
            mIntent.putExtras(bundle);
        }
        if (getPackageManager().resolveActivity(mIntent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            this.startActivity(mIntent);
        } else {
            LogUtils.e("activity not found for " + className.getSimpleName());
        }
    }


    public void startActivityForResult(Class<?> className, int requestCode) {
        startActivityForResult(className, null, requestCode);
    }

    /**
     * activity 跳转带回调[有参]
     *
     * @param className
     * @param bundle
     * @param requestCode
     */
    public void startActivityForResult(Class<?> className, Bundle bundle,
                                       int requestCode) {
        Intent mIntent = new Intent();
        mIntent.setClass(this, className);
        if (bundle != null) {
            mIntent.putExtras(bundle);
        }
        if (getPackageManager().resolveActivity(mIntent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            startActivityForResult(mIntent, requestCode);
        } else {
            LogUtils.e("activity not found for " + className.getSimpleName());
        }
    }

    class ForceOffLineReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(R.string.sys_caveat);
            builder.setMessage(R.string.sys_device);
            builder.setCancelable(false); // 将对话框设置为不可取消
            // 给按钮添加注册监听
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // 点击按钮所调用的方法
                    AppManager.getAppManager().staLoginActivity();
                }
            });
            builder.show();
        }
    }
}
